﻿using BoardBroker;
using KCommon;
using KXmlUIControl;
using LogLib;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace ResettingTool
{
    public partial class FormTool : Form
    {
        protected List<XmlProgramObject> Programs = null;

        /// <summary>
        /// 电机控制对象
        /// </summary>
        protected BoardControl _board = null;

        public FormTool()
        {
            InitializeComponent();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        private void buttonKillAll_Click(object sender, EventArgs e)
        {
            foreach (XmlProgramObject p in Programs)
            {
                if (!p.Name.Equals("MotionControl"))
                {
                    ExitProcess(p.Name);
                }
            }
            buttonCloseMotion.PerformClick();
            ExitProcess("IPT");
        }

        private void buttonShowTaskbar_Click(object sender, EventArgs e)
        {
            ShowTaskBar(true);
            ShowStartButton(true);
        }
        //SendMotionForReset();

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadConfigData();
            CreatMotionControl();
        }

        private void LoadConfigData()
        {
            string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Substring(6);
            DirectoryInfo dir = new DirectoryInfo(directory);
            string xmlFile = string.Format("{0}\\config\\MainForm.xml", dir.FullName);
            if (!File.Exists(xmlFile))
            {
                return;
            }
            XmlConfigApplication configFile = new XmlConfigApplication(xmlFile);
            configFile.OnReading();
            Programs = configFile.ListPrograms;
        }

        protected static void ExitProcess(string processName)
        {
            Process[] processes = Process.GetProcesses();
            foreach (Process p in processes)
            {
                try
                {
                    if (p.ProcessName.ToUpper() == processName.ToUpper())
                    {
                        Log.WriteAsync("进程" + processName + "已存在");
                        p.Kill();
                        p.WaitForExit();
                        p.Close();
                        Log.WriteAsync("进程" + processName + "已关闭");
                    }
                }
                catch (Exception ex)
                {
                    Log.WriteException(ex.ToString());
                }
            }
        }

        private void ShowTaskBar(bool showCode)
        {
            IntPtr hwnd = IntPtr.Zero;
            hwnd = WinAPI.FindWindow("Shell_TrayWnd", "");//获取任务栏的句柄
            if (hwnd == IntPtr.Zero) return;
            if (showCode)
            {
                WinAPI.ShowWindow(hwnd, (int)ShowCommands.SW_SHOW);//显示任务栏
            }
            else
            {
                WinAPI.ShowWindow(hwnd, (int)ShowCommands.SW_HIDE);//隐藏任务栏
            }
        }

        private void ShowStartButton(bool showCode)
        {
            IntPtr hwnd = IntPtr.Zero;
            hwnd = WinAPI.FindWindowEx(IntPtr.Zero, IntPtr.Zero, "Button", "开始");//获取开始按钮的句柄
            if (hwnd == IntPtr.Zero) return;
            if (showCode)
            {
                WinAPI.ShowWindow(hwnd, (int)ShowCommands.SW_SHOW);//显示开始按钮
            }
            else
            {
                WinAPI.ShowWindow(hwnd, (int)ShowCommands.SW_HIDE);//隐藏开始按钮
            }
        }

        #region Motion Control
        /// <summary>
        /// 创建电机代理控制对象
        /// </summary>
        private void CreatMotionControl()
        {
            // 创建电机代理控制对象
            BoardControl.CreatInstance();
            _board = BoardControl.Instance;
        }

        #endregion

        private void buttonCloseMotion_Click(object sender, EventArgs e)
        {
            bool bRet1 = _board.FindUSBControlWindowHandle();
            bool bRet2 = _board.FindLedControlWindowHandle();
            if (bRet1 || bRet2)
            {
                _board.CloseDevice();
            }
            else
            {
                //MessageBox.Show("未能找到电机运动控制程序!");
            }            
        }

        private void buttonResetDevice_Click(object sender, EventArgs e)
        {
            if (_board.FindLedControlWindowHandle())
            {
                _board.StopWorking();
            }
            else
            {
                //MessageBox.Show("未能找到电机运动控制程序!");
            }
        }

        private void buttonResetScreen_Click(object sender, EventArgs e)
        {
            SendKeys.Send("^%{UP}");
        }
    }
}
